package cn.edu.zut.internship.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
@Component
public class PrimaryKeyUtil {
    @Autowired
    private RedisTemplate redisTemplate;
    private String getOrderIdPrefix(Date date) {
        //生成日期的字符串
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //补两位,因为一年最多三位数
        String monthFormat = String.format("%1$02d", month+1);
        //补两位，因为日最多两位数
        String dayFormat = String.format("%1$02d", day);
        //补两位，因为小时最多两位数
        String hourFormat = String.format("%1$02d", hour);
        return year + monthFormat + dayFormat+hourFormat;
    }
    /**
     * 生成主键Id
     * @param tableName
     * @return
     */
    public Long generatePrimaryKey(String tableName) {
        String key = "INTERNSHIP_Key" + tableName;
        String primaryKey = null;
        try {
            Long increment = redisTemplate.opsForValue().increment(key,1);
            //往前补6位
            String prefix = getOrderIdPrefix(new Date());
            primaryKey=prefix+String.format("%1$06d",increment);
        } catch (Exception e) {
            System.out.println("主键Id失败");
            e.printStackTrace();
        }
        return Long.valueOf(primaryKey);
    }
}
